# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
  def track_appendable_field(field, selector)
    javascript_tag <<-EOT
        new AppendableSelect('#{field}', '#{selector}');
    EOT
  end
  
  def function(name, params) 
    page.send :record, "function #{name}(#{params.collect {|x| x.to_s}.join(', ')}) {"
    yield
    page.send :record, "}"
  end
  
  def confirm(prompt)
    page << "if(!confirm(" + page.send(:arguments_for_call, [prompt]) + ")) return false;"
  end
  
  class LayoutDomItem
    attr_accessor :id, :children, :attributes, :text
    
    include Enumerable
    
    def initialize
      @children = []
      @attributes = {}
    end
    
    def [](id)
      @children.find {|c| c.id == id}
    end
    
    def elements(id)
      @children.select {|c| c.id == id}
    end
        
    def each(&block)
      @children.each(&block)
    end
    
    def method_missing(id)
      attributes[id] || (r = self[id]) && r.text
    end
  end
  
  class LayoutDomBuilder
    attr_reader :items, :erbout, :root_items
    
    def initialize(&block)
      @erbout = eval('_erbout', block.binding)
      @items = []
      @root_items = []
    end
    
    def method_missing(id, *attributes, &block)
      last_item = LayoutDomItem.new
      if @items.empty? then @root_items else @items.last.children end << last_item
      @items << last_item
      last_item.id = id
      last_item.attributes = attributes
      
      level = @erbout.length
      yield self
      last_item.text = @erbout[level..-1]
      # last_item.text = nil if 0 == last_item.text.length
      @erbout[level..-1] = ''
      
      @items.pop
    end
    
    def root_item
      return nil if @root_items.empty?
      @root_items.first
    end
    
  end
  
  def widget(id, *attributes, &block)
    builder = LayoutDomBuilder.new(&block)
    builder.method_missing(id, *attributes, &block)
    # builder.erbout << "<pre>" + h(builder.root_item.to_yaml) + "</pre>\n"
    builder.erbout << render(:partial => "widgets/#{id}", :locals => {:data => builder.root_item})
  end
end
